package ph.gov.marikina.mcsmtms.dao.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import ph.gov.marikina.mcsmtms.constants.GlobalConstants.UserTypes;
import ph.gov.marikina.mcsmtms.dao.UserDAO;
import ph.gov.marikina.mcsmtms.domain.User;

// TODO: Auto-generated Javadoc
/**
 * The Class UserDAOImpl.
 */
@Transactional
@Repository
public class UserDAOImpl implements UserDAO {
	

	/** The find by user id sql. */
	final String FIND_BY_USER_ID_SQL = "select * from user where id = ?";
	
	/** The insert query sql. */
	final String INSERT_QUERY_SQL = "INSERT INTO USER (NAME, USER_TYPE, MOBILE_NUMBER, USERNAME, PASSWORD, MOBILE_ALERT) VALUES (?, ?, ?, ?, ?, ?);";
	
	/** The select all. */
	final String SELECT_ALL = "select * from user";
	
	/** The login user. */
	final String LOGIN_USER = "select username, password, name, user_type from user where username = ? and password = ?";
	
	final String FIND_BY_USER_TYPE_SQL = "SELECT * FROM USER WHERE mobile_alert = 1 and mobile_number is not null";
	
	/** The log. */
	Logger log = Logger.getLogger(UserDAOImpl.class);
	
	private SessionFactory sessionFactory;
	
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
//	@Transactional(readOnly=false)
//	public void addPerson(Person p) {
//		Session session = sessionFactory.openSession();
//		session.save(p);
//		session.close();		
//	}

	/* (non-Javadoc)
	 * @see ph.gov.marikina.mcdrrmo.dao.UserDAO#insert(ph.gov.marikina.mcdrrmo.domain.User)
	 */
	@Transactional(readOnly=false)
	public void addUser(User user) {
//		getJdbcTemplate().update(
//				INSERT_QUERY_SQL,
//				new Object[] { user.getFullName(), user.getUserType(),
//						user.getMobileNumber(), user.getUserName(),
//						user.getPassword(), user.isHasMobileAlert() });
		Session session = sessionFactory.openSession();
		session.save(user);
		session.close();
	}

	/* (non-Javadoc)
	 * @see ph.gov.marikina.mcdrrmo.dao.UserDAO#findByUserID(int)
	 */
	@Override
	public User findByUserID(int id) {
//		JdbcTemplate select = new JdbcTemplate(getDataSource());
//		return select.queryForObject(FIND_BY_USER_ID_SQL, new Object[] { id },
//				new UserRowMapper());
		return null;
	}

	/* (non-Javadoc)
	 * @see ph.gov.marikina.mcdrrmo.dao.UserDAO#deleteAll()
	 */
	@Override
	public void deleteAll() {
		// TODO Auto-generated method stub

	}

	/* (non-Javadoc)
	 * @see ph.gov.marikina.mcdrrmo.dao.UserDAO#selectAll()
	 */
	@Override
	public User selectAll() {
//		JdbcTemplate select = new JdbcTemplate(getDataSource());
//		return select.queryForObject(SELECT_ALL, new UserRowMapper());
		return null;
	}

	/* (non-Javadoc)
	 * @see ph.gov.marikina.mcdrrmo.dao.UserDAO#login(ph.gov.marikina.mcdrrmo.domain.User)
	 */
	@SuppressWarnings("unchecked")
	public List<User> findUser(User user) {
//		JdbcTemplate select = new JdbcTemplate(getDataSource());
//		return select.queryForObject(LOGIN_USER, new Object[] { user.getId(), user.getPassword() }, new LoginRowMapper());
		Query query = this.sessionFactory.getCurrentSession()
                .createQuery("from User where username=? and password=?");
//                .setPara
//                .list();
		query.setParameter(0, user.getId());
		query.setParameter(1, user.getPassword());
		
		return (List<User>) query.list();
	}
	
	public User loginUser(User user) {
		Query query = this.sessionFactory.getCurrentSession()
                .createQuery("from User where username=? and password=?");
//                .setPara
//                .list();
		query.setParameter(0, user.getUserName());
		query.setParameter(1, user.getPassword());
		
		if(query.list() != null &&  query.list().size() > 0) {
			return (User) query.list().get(0);
		} else {
			return null;
		} 
	}
	
	public User getUser(String username) {
//		JdbcTemplate select = new JdbcTemplate(getDataSource());
//		return select.queryForObject(LOGIN_USER, new Object[] { user.getId(), user.getPassword() }, new LoginRowMapper());
		Query query = this.sessionFactory.getCurrentSession()
                .createQuery("from User where username=?");
		query.setParameter(0, username);
		
		if(query.list() != null && query.list().size() > 0)
			return (User) query.list().get(0);
		else return null;
	}

	/* (non-Javadoc)
	 * @see ph.gov.marikina.mcdrrmo.dao.UserDAO#findAlertUsers()
	 */
	@Override
	public List<User> getAlertUsers() {
		Query query = this.sessionFactory.getCurrentSession()
                .createQuery("from User where hasMobileAlert=? and userType=?");

		query.setParameter(0, true);
		query.setParameter(1, UserTypes.USER.getCode());
		
		if(query.list() != null &&  query.list().size() > 0) {
			return (List<User>) query.list();
		} else {
			return null;
		}
	}
	
	@Transactional(readOnly=false)
	@Override
	public void updateUser(User user) {
		Session session = sessionFactory.openSession();
	    Transaction tx = null;
	    try{
	    	tx = session.beginTransaction();
	    	session.update(user); 
	    	tx.commit();
	    }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	    } finally {
	         session.close(); 
	    }
	}
}
